﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace JHoelsch.DataClases.Serialization
{
    public class XmlSerializationTool
    {
        static public void writeToFile<T>(T toSave, string filename) 
        {
            if (toSave == null)
                return;                    
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(toSave.GetType());
            XmlWriterSettings oSettings = new XmlWriterSettings();
            oSettings.Indent = true;
            oSettings.OmitXmlDeclaration = true;
            oSettings.Encoding = Encoding.UTF8;
            oSettings.CloseOutput = true;
            using (XmlWriter writer = XmlWriter.Create(System.IO.File.Create(filename), oSettings))
            {
                try
                {
                    System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
                    ns.Add("", "");
                    x.Serialize(writer, toSave, ns);
                    writer.Flush();
                    writer.Close();
                }
                catch (Exception exc)
                {
                    System.Diagnostics.Debug.WriteLine(exc.StackTrace);
                }
            }
        }
        public static T readFromFile<T>(string filename) where T : new()
        {
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.CloseInput = true;
            if(System.IO.File.Exists(filename))
            using (XmlReader reader = XmlReader.Create(filename, settings))
            {
                try
                {
                    if (x.CanDeserialize(reader))
                        return (T)x.Deserialize(reader);
                }
                catch (Exception exc)
                {
                    System.Diagnostics.Debug.WriteLine(exc.StackTrace);
                }
                reader.Close();
            }
            return default(T);
        }
    }
}
